<?php

namespace App\Http\Controllers\Common;

use App\Exports\DemoExport;
use App\Http\Controllers\Controller;
use App\Imports\DemoImport;
use App\Models\Constant\UploadConstant;
use App\Models\Flight\FlightInfo;
use App\Models\Flight\Order;
use Barryvdh\Snappy\Facades\SnappyPdf as PDF;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use Kkokk\Poster\PosterManager;
use Maatwebsite\Excel\Facades\Excel;

abstract class CommonController extends Controller {

    protected $getCol = ['*'];

    public function getToken(Request $request){
        $id = $request->input('id');
        $this->validate($request, ['id'=>'required']);
        $token = generateJWT(['id'=>$id]);
        return responseSuccess(compact('id','token'));
    }


    protected function getQr(string $name,string $content ){
        $path = "/storage/qr/$name.png";
        if(file_exists(public_path($path))){
            return $path;
        }
        $qr = PosterManager::Poster()->Qr($content,public_path($path));
        return $path;
    }

    public function download(Request $request) {
        Log::info('p',$request->input());
        $downloadType = $request->input('downloadType');
        $this->validate($request, ['downloadType'=>'required']);
        $conditions = $request->input();
        unset($conditions['downloadType']);
        if($downloadType=='flight'){
            return Excel::download(new DemoExport($conditions),$downloadType.time().'.xlsx');
        }elseif ($downloadType=='muban'){
            return response()->download(public_path('Newest.xlsx'));
        } else{

            $code = $request->input('code');
            $records = Order::query()->where(['code'=>$code,'is_hide'=>0])->with('getFlightInfo')->get();
            $firstRecord = $records->first();
            $createdAt = Carbon::parse(date('Y-m-d',strtotime($firstRecord->created_at)))->format('D j M Y');
            $isDouble = $firstRecord->is_double;
            $flightInfos = [];
            $passengers = [];
            $extra = [];
            $flight = FlightInfo::query()->where('id',$firstRecord->flight_id)->first();
            $during = Carbon::parse($flight->start_fly_time)->diffInMinutes(Carbon::parse($flight->end_fly_time));
            //=============================== 航班 ===========================================================
            $flightInfos[] = [
                'date'=>Carbon::parse($flight->date)->format('l j F Y'),
                'flight_no'=>$flight->flight_no,
                'simple_start_airport'=>$flight->start_airport,
                'simple_end_airport'=>$flight->end_airport,
                'full_start_airport'=>getFullAirport($flight->start_airport),
                'full_end_airport'=>getFullAirport($flight->end_airport),
                'start_airport'=>getAirport($flight->start_airport),
                'end_airport'=>getAirport($flight->end_airport),
                'start_fly_time'=>$flight->start_fly_time,
                'end_fly_time'=>$flight->end_fly_time,
                'during'=>toHumanHours($during)
            ];
            //往返航班
            if($isDouble==1){
                $coupleFlight = FlightInfo::query()->where('id',$firstRecord->couple_flight_id)->first();
                $during = Carbon::parse($coupleFlight->start_fly_time)->diffInMinutes(Carbon::parse($coupleFlight->end_fly_time));
                $flightInfos[] = [
                    'date'=>Carbon::parse($coupleFlight->date)->format('l j F Y'),
                    'flight_no'=>$coupleFlight->flight_no,
                    'simple_start_airport'=>$coupleFlight->start_airport,
                    'simple_end_airport'=>$coupleFlight->end_airport,
                    'full_start_airport'=>getFullAirport($coupleFlight->start_airport),
                    'full_end_airport'=>getFullAirport($coupleFlight->end_airport),
                    'start_airport'=>getAirport($coupleFlight->start_airport),
                    'end_airport'=>getAirport($coupleFlight->end_airport),
                    'start_fly_time'=>$coupleFlight->start_fly_time,
                    'end_fly_time'=>$coupleFlight->end_fly_time,
                    'during'=>toHumanHours($during)
                ];
            }
            //=============================== 乘客 ===========================================================
            foreach ($records as $record) {
                $passengers[] = [
                    'sub_name'=>getSubName($record->name),
                    'name'=>implode(' ', array_reverse(explode(' ', $record->name))),
                    'type'=>getPassengerTypeForEnglish($record->passenger_type,$record->passenger_sex),
                ];
            }
            //=============================== Extra services ===========================================================
            $strContent = $this->qrCode($code);
            $text = $strContent;
            $imgName = time().uniqid().'.png';
            $subPath = "qr/$imgName";
            $absPath = public_path($subPath);
            PosterManager::Poster()->Qr($text,$absPath);

            $imageData = file_get_contents($absPath);
            $img64 = base64_encode($imageData);

            //Log::info('ff',[$img64]);

            $pdf = PDF::loadView('order',compact('img64','firstRecord','isDouble','createdAt','flightInfos','passengers')); // welcome 为html 页面
            $pdf->setOption('encoding', 'utf-8');
            //$pdf->setOption('encoding', 'gb18030');
            $pdf->setOption('enable-local-file-access', true)->setPaper('a4'); // welcome 页面引入本地静态资源后使用，否则生成pdf时test引入本地静态资源失败（例如：本地字体）
            $fileName = $firstRecord->name;
            if(empty($fileName))$fileName=Str::random(10);
            return $pdf->download($fileName.'.pdf');
        }
    }

    public function importFile(Request $request) {
        $token = $request->input('token');
         $id = checkJWT($token)['id'];
        /* $guardUser = GuardUser::where(compact('id'))->first();
        if(empty($guardUser)){
            return responseFail('当前用户无效！');
        }*/
        $importType = $request->input('importType');
        $this->validate($request, ['importType'=>'required']);
        $file = $request->file('file');
        if(empty($file) || !$file->isValid()){
            return responseFail('文件无效！');
        }
        $path = $file->store($importType,'upload');

        if($importType=='flight'){

            $import = new DemoImport(compact('id'));
        }
        //TODO 继续添加if

        Excel::import($import, storage_path('app/public/upload/'.$path));
        $count = $import->count;
        $countSuccess = $import->countSuccess;
        $countFail = $import->countFail;
        $success = $import->success;
        $msg = $import->msg;
        if($success){
            return responseSuccess(compact('count','countSuccess','countFail'),0,$msg);
        }else{
            return responseFail();
        }
    }

    public function upload(Request $request){
        $file = $request->file('file');
        $count = $request->input('count',0);
        if(empty($file) || !$file->isValid()){
            return responseFail('文件无效！');
        }
        $size =  $file->getSize();
        $ext = $file->getClientOriginalExtension();
        $originName = $file->getClientOriginalName();
        $module = $request->input('module','default');
        $type = $request->input('type','default');

        //检查目录
        $middlePath = "/$module/".date('Y-m-d');
        $absDir = Storage::disk('upload')->path($middlePath);
        if(!is_dir($absDir)){mkdir($absDir,0777,true);}

        //重命名
        $fileName = time().uniqid().".$ext";

        //如果是图片
        if(in_array($ext, UploadConstant::mapPic)){

            if($request->has('w')){
                $w = $request->input('w');
                $h = $request->input('h');
                if(!empty($w) && !empty($h)){
                    $this->validate($request, [
                        'file' => 'mimes:jpeg,bmp,png,gif,webp|dimensions:width='.$w.',height='.$h,
                    ],[],['w'=>'宽', 'h'=>'高',]);
                }
            }

            $imgIsCut = $request->input('imgIsCut',env('IMG_IS_CUT',false));//是否需要压缩
            $imgIsCutSize = $request->input('imgIsCutSize',env('IMG_IS_CUT_SIZE',1024*1024*1));//压缩阈值
            $imgCutRatio = $request->input('imgCutRatio',env('IMG_CUT_RATION',700));//压缩比

            //如果需要压缩
            if($imgIsCut && $size>=$imgIsCutSize){
                $fileName = time().uniqid().'.jpg';
                $rs = Image::make($file->getRealPath())->resize($imgCutRatio, $imgCutRatio, function ($constraint) {
                    $constraint->aspectRatio();
                })->save($absDir."/$fileName");
                if($rs === false){
                    return responseFail('图片压缩失败');
                }
                $filePath = "$middlePath/$fileName";
            }else{
                $filePath = $file->storeAs($middlePath,$fileName,'upload');
            }
        }
        //如果是文件
        else{
            $filePath = $file->storeAs($middlePath,$fileName,'upload');
        }

        $filePath = Str::replace('//', '/', '/storage/upload/'.$filePath);
        $url = asset($filePath);

        if(in_array($ext, UploadConstant::mapVideo)){
            $url = asset('/common/image/cover.png');
        }

        return responseSuccess(compact('type','filePath','count','size','url','originName','ext','fileName'));
    }

    public function getDetail($model, array $ids,array $cols=['*']){
        return $model::whereIn('id',$ids)->get($cols);
    }

    protected function changeCol($model,array $keyNames,array $keyValues,array $colNames,array $colValues) {
        foreach ($keyNames as $k=>$keyName) {
            $model::where($keyName,$keyValues[$k])->update([$colNames[$k]=>$colValues[$k]]);
        }
        return responseSuccess();
    }

    protected function changeColByIds($model,array $ids,array $colKeyValue) {
        $model::whereIn('id',$ids)->update($colKeyValue);
        return responseSuccess();
    }

    protected function delRecords($model,array $ids,$isForce=false) {

        if(count($ids)<=0) return responseSuccess();

        if($isForce){
            $model::whereIn('id',$ids)->forceDelete();
        }else{
            $model::whereIn('id',$ids)->delete();
        }
        return responseSuccess();
    }

    protected function handleChildren(&$records) {
        foreach ($records as $record) {
            if(count($record['children'])<=0){
                unset($record['children']);
            }else{
                $this->handleChildren($record['children']);
            }
        }
    }

    /**
     * @deprecated
     * @param $model
     * @param array $ids
     * @return \Illuminate\Http\JsonResponse
     */
    protected function getRecordByIds($model, array $ids) {
        $records = $model::whereIn('id',$ids)->get();
        return responseSuccess($records->toArray());
    }

}
